import React, { Component } from 'react';
import { Text, TabBarIOS, StyleSheet, View, Image, InteractionManager,Dimensions } from 'react-native';
import TabNavigator from 'react-native-tab-navigator';

import Colors from '../../common/Colors';
import SizeUtils from '../../common/SizeUtils';
import Constants from '../../common/Constants';
import ToastUtils from '../../common/ToastUtils';
import Config from '../../config';
import IndexView from './IndexView';
import NewsView from './NewsView';
import QuanziView from './QuanziView';
import JianyiView from './JianyiView';
import QZ_WelcomeView from '../quanzi/QZ_WelcomeView';
import UserView from './UserView';
import UsualView from './UsualView';
import BasePage from '../common/BasePage';
import EventManager from '../../events/EventManager';
import Event from '../../events/Event';
import CommonShowViewFullScreenAction from '../../actions/common/CommonShowViewFullScreenAction';
import QZ_RequestQuanziListAction from '../../actions/quanzi/QZ_RequestQuanziListAction';
import LoginCheckIsUserAction from '../../actions/login/LoginCheckIsUserAction';

var Orientation = require('react-native-orientation');
var homeTabs = {
  index: {
    key: 'index',
    value: '首页',
    title: '大庆油田工会',
    icon: require('../../../resource/images/home/tabbar/shouye.png'),
    iconSelected: require('../../../resource/images/home/tabbar/shouye_s.png'),
    width: 50,
    height: 50
  },
  news: {
    key: 'news',
    value: '新闻',
    title: '新闻',
    icon: require('../../../resource/images/home/tabbar/xinwen.png'),
    iconSelected: require('../../../resource/images/home/tabbar/xinwen_s.png'),
    width: 50,
    height: 50
  },
  usual: {
    key: 'usual',
    value: '常用',
    title: '常用',
    icon: require('../../../resource/images/home/tabbar/changyong_gray.png'),
    iconSelected: require('../../../resource/images/home/tabbar/changyong_red.png'),
    width: 40,
    height: 40
  },
  quanzi: {
    key: 'quanzi',
    value: '圈子',
    title: '圈子',
    icon: require('../../../resource/images/home/tabbar/quanzi.png'),
    iconSelected: require('../../../resource/images/home/tabbar/quanzi_s.png'),
    width: 50,
    height: 50
  },
  jianyi: {
    key: 'jianyi',
    value: '建议',
    title: '建议',
    icon: require('../../../resource/images/home/tabbar/quanzi.png'),
    iconSelected: require('../../../resource/images/home/tabbar/quanzi_s.png'),
    width: 50,
    height: 50
  },
  user: {
    key: 'user',
    value: '我的',
    title: '个人信息',
    icon: require('../../../resource/images/home/tabbar/wode.png'),
    iconSelected: require('../../../resource/images/home/tabbar/wode_s.png'),
    width: 50,
    height: 50
  }
};
// var TabBarDic = [homeTabs.index, homeTabs.news, homeTabs.user];
//var TabBarDic = [homeTabs.index, homeTabs.news, homeTabs.usual, homeTabs.quanzi, homeTabs.user];
var TabBarDic = [homeTabs.index, homeTabs.news, homeTabs.jianyi, homeTabs.user];

global.isIphonex=(Dimensions.get('window').height===812)?true:false;

export default class HomePage extends BasePage {
  constructor(props) {
    super(props);
    this.state = {
      selectedTab: TabBarDic[0],
      leave: false,
      quanziShowWelcom: false,
      componentReady: false
    };
    this._homeEventDispatcher = EventManager.getEventDispather(Constants.MODULE_TYPE.HOME);
    new QZ_RequestQuanziListAction().call({ setState: function() {} }, { page: 1 });

    this._viewRef = {};

    this._changeTabMark = 0;
  }

  _changeTab(selectedTab) {
    this._changeTabMark++;
    if (selectedTab.key === homeTabs.usual.key) {
      new CommonShowViewFullScreenAction().call(this, {
        component: UsualView,
        page: this,
        updateMark: this._changeTabMark
      });
    } else if (selectedTab.key === homeTabs.quanzi.key) {
      new LoginCheckIsUserAction().call(this, { content: '你是游客身份，不能使用此功能' }, result => {
        if (result) {
          this._viewRef[homeTabs.index.key] &&
            this._viewRef[homeTabs.index.key].setMuduVisible(
              selectedTab.key === homeTabs.index.key
            );
          this.setState({ selectedTab });
        }
      });
    } else {
      this._viewRef[homeTabs.index.key] &&
        this._viewRef[homeTabs.index.key].setMuduVisible(selectedTab.key === homeTabs.index.key);
      this.setState({
        selectedTab
      });
    }
  }

  componentDidMount() {
    Orientation.lockToPortrait();
    InteractionManager.runAfterInteractions(() => {
      this.setState({
        componentReady: true,
      })
    })
  }

  componentDidUpdate(prevProps, prevState) {
    Orientation.lockToPortrait();
  }

  componentWillUnmount() {
    this._viewRef = null;
  }

  render() {
    if (!this.state.componentReady) {
      return <View />
    }
    return (
      <TabNavigator
        tabBarStyle={{ backgroundColor: 'white',height:global.isIphonex?68:54,paddingBottom:global.isIphonex?20:4,}}
        style={{
          paddingBottom: 0,
          backgroundColor: 'white',
          height: SizeUtils.translateDesignWidthToCode(98)
        }}
      >
        {TabBarDic.map((item, index) => {
          return this._getTabItem(item, index);
        })}
      </TabNavigator>
    );
  }

  _dealEnterPage() {
    if (this._authorization != this.props.pageData.routeData.authorization) {
      this._authorization = this.props.pageData.routeData.authorization;
    }
  }

  _getTabItem(tabBarData, index) {
    // console.log("_getTabItem", tabBarData);
    return (
      <TabNavigator.Item
        key={index}
        style={{
          padding: 0,
          height: SizeUtils.translateDesignHeightToCode(98)
        }}
        selected={this.state.selectedTab === tabBarData}
        title={tabBarData.value}
        titleStyle={{
          padding: 0,
          fontSize: SizeUtils.translateFontSizeToCode(20),
          borderWidth: 0,
          backgroundColor: '#00000000'
        }}
        selectedTitleStyle={{ padding: 0, color: '#db3132' }}
        renderIcon={() => this._renderIcon(tabBarData)}
        renderSelectedIcon={() => this._renderSelectedIcon(tabBarData)}
        onPress={() => this._changeTab(tabBarData)}
      >
        {this._getPage(tabBarData)}
      </TabNavigator.Item>
    );
  }

  _renderSelectedIcon(tabBarData) {
    return (
      <View
        style={{
          width: SizeUtils.translateDesignWidthToCode(50),
          height: SizeUtils.translateDesignWidthToCode(50),
          flexDirection: 'row',
          justifyContent: 'center',
          alignItems: 'center'
        }}
      >
        <Image
          source={tabBarData.iconSelected}
          style={{
            width: SizeUtils.translateDesignWidthToCode(tabBarData.width),
            height: SizeUtils.translateDesignWidthToCode(tabBarData.height)
          }}
        />
      </View>
    );
  }

  _renderIcon(tabBarData) {
    return (
      <View
        style={{
          width: SizeUtils.translateDesignWidthToCode(50),
          height: SizeUtils.translateDesignWidthToCode(50),
          flexDirection: 'row',
          justifyContent: 'center',
          alignItems: 'center'
        }}
      >
        <Image
          source={tabBarData.icon}
          style={{
            width: SizeUtils.translateDesignWidthToCode(tabBarData.width),
            height: SizeUtils.translateDesignWidthToCode(tabBarData.height)
          }}
        />
      </View>
    );
  }

  _getPage(tabBarData) {
    // console.log("_getPage", tabBarData);
    var view = { component: null };
    if (tabBarData.key === homeTabs.index.key) {
      view.component = IndexView;
    } else if (tabBarData.key === homeTabs.news.key) {
      view.component = NewsView;
    } else if (tabBarData.key === homeTabs.quanzi.key) {
      if (!Constants.IS_WELLCOME) {
        view.component = QZ_WelcomeView;
        Constants.homePageCallBack = this._reloadWelCome.bind(this);
      } else {
        view.component = QuanziView;
      }
    } else if (tabBarData.key === homeTabs.jianyi.key) {
      view.component = JianyiView;
    } else if (tabBarData.key === homeTabs.user.key) {
      view.component = UserView;
    } else if (tabBarData.key === homeTabs.usual.key) {
      view.component = View;
    }
    if (view.component == null) {
      view.component = View;
    }
    let height =
      SizeUtils.getWindowSize().height -
      SizeUtils.translateDesignHeightToCode(98) -
      Config.paddingTop;
    return (
      <view.component
        style={{ height: height }}
        ref={ref => this._setComponentRef(ref, tabBarData)}
        authorization={this.props.pageData.routeData.authorization}
        data={tabBarData}
        pageData={this.props.pageData}
        leave={this.state.leave}
        notificationCall={params => this._notificationCall(params, tabBarData)}
      />
    );
  }

  _setComponentRef(ref, tabBarData) {
    if (this._viewRef && ref) {
      this._viewRef[tabBarData.key] = ref;
    }
  }

  _notificationCall(params, tabBarData) {
    if (params.type === 'changeTab') {
      if (params.value === 'news') {
        this._changeTab(homeTabs.news);
      }
    } else if (tabBarData.key === homeTabs.index.key) {
    }
  }

  _reloadWelCome() {
    this.setState({
      quanziShowWelcom: false
    });
  }
}

const styles = StyleSheet.create({
  tabSelectedstyle: {},

  titleStyle: {},

  titleSelected: {}
});
